/**
 * @FileName: DblUtils.java
 * @Package:com.bdtop.dbl.utils
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-29
 * @version V1.0
 */

package com.bdtop.dbl.utils;

import java.text.DecimalFormat;

/**
 * @ClassName: DblUtils
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-29
 */
public class DblUtils {

	public static final int txPowerAtSource = -25;

	public static double distanceFromRssi(int rssi) {
		// Path loss
		int pathLoss = txPowerAtSource - rssi;

		// Distance calculation
		double distance = Math.pow(10, (pathLoss - 41) / 20.0);

		// Remain .00
		DecimalFormat df = new DecimalFormat("0.00");
		return new Double(df.format(distance));
	}

	public static boolean isEq(byte[] byte1, byte[] byte2) {
		if (byte1 == null || byte2 == null) {
			return false;
		}
		if (byte1.length != byte2.length) {
			return false;
		}
		for (int i = 0; i < byte2.length; i++) {
			if (byte1[i] != byte2[i]) {
				return false;
			}
		}
		return true;
	}

	// /**
	// * TODO To be fixed
	// *
	// * @param @param rssi
	// * @param @return
	// * @return double
	// * @throws
	// */
	// public static float convertRssiToDistance(int rssi) {
	// int abs = Math.abs(rssi);
	//
	// if (abs < 60) {
	// return 1.0f;
	// } else if (abs < 70) {
	// return 3.0f;
	// } else if (abs < 80) {
	// return 5.0f;
	// } else if (abs < 100) {
	// return 10.0f;
	// } else if (abs < 120) {
	// return 15.0f;
	// } else {
	// return 30.0f;
	// }
	// }

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}
}
